<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               v-model="form"
               ref="crud"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">
      <template slot="menuLeft">
        <el-button type="warning" size="small" plain icon="el-icon-download" @click="exportBusinessMonth">导出
        </el-button>
      </template>
    </avue-crud>

  </basic-container>
</template>


<script>
import {declarationCompanyStatisticsList, exportDeclarationCompany} from "@/api/business/batchOrder";

export default {
  data() {
    return {
      dateRange: {
        beginTime: "",
        endTime: ""
      },
      monthValue: '',
      search: {
        billYear: [],
        district: '',
        companyName:'',
        companyId:'',
      },
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        searchSpan: 4,
        searchLabelWidth: 80,
        emptyBtn: false,
        addBtn: false,
        menu: false,
        columnBtn: false,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: false,
        selection: false,
        //menuWidth: 1,
        column: [
          {
            label: "采购月份",
            prop: "month",
            format: "yyyy-MM",
            valueFormat: "yyyy-MM",
            type: 'month',
            searchSpan: 6,
            searchRange: true,
            search: true,
            searchValue: [],
            searchClearable: false,
            hide: true,
          },
          {
            label: "区县",
            prop: "district",
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=medpur_institution",
            dataType: "string",
            searchGutter: 1,
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            search: true,
            searchLabelWidth:50,
            overHidden: true,
            hide: true,
          },
          {
            label: "企业编号",
            prop: "companyId",

            search: true,
            searchSpan: 4,
          },
          {
            label: "企业名称",
            prop: "companyName",
            search: true,
          },
          {
            label: "采购医药机构数",
            prop: "instSum",
          },
          {
            label: "品规数",
            prop: "medicineSum",
            //fixed: "right",//列是否固定在左侧或者右侧，true 表示固定在左侧
          },
          {
            label: "入库数量",
            prop: "actualDeliver",
          },
          {
            label: "入库金额 (元)",
            prop: "actualFee",
          },

        ]
      },
      data: []
    };
  },

  methods: {
    exportBusinessMonth() {
      const month = this.query.month;
      const district = this.query.district;
      const companyId = this.query.companyId;
      const companyName = this.query.companyName;

      let fileName;

      if (month !== undefined) {
        fileName = '荆州市' + month[0] + '月份至' + month[1] + '月份按地区汇总统计';
      } else {
        const currentDate = new Date();
        const currentYearMonth = this.getYearMonthString(currentDate);
        const previousDate = new Date(currentDate.getFullYear(), currentDate.getMonth() - 2);
        const previousYearMonth = this.getYearMonthString(previousDate);
        fileName = '荆州市' + previousYearMonth + '月份至' + currentYearMonth + '月份按地区汇总统计';
      }

      const length = this.search.billYear.length;
      if (length > 0) {
        this.search.billYear[length - 1] = month;
      } else {
        this.search.billYear.push(month);
      }

      const searchParams = {...this.search, district,companyId,companyName};
      searchParams.sheetName = fileName;
      this.loading = true;

      exportDeclarationCompany(searchParams, month)
        .then((exp) => {
          // console.log(exp.request.response);
          if (exp.request.response.size > 0) {
            if (exp.status !== 200) {
              this.$message.warning("导出数据异常");
              this.loading = false;
              return;
            }
            const url = window.URL.createObjectURL(exp.request.response);
            const a = document.createElement('a');
            document.body.appendChild(a);
            a.href = url;
            a.download = fileName;
            a.click();
            window.URL.revokeObjectURL(url);
            this.loading = false;
          } else {
            this.$message.warning('导出失败!');
          }
        })
        .catch((err) => {
          console.log(err);
        });
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      const date1 = new Date(params.month[0]);
      const date2 = new Date(params.month[1]);
      const yearDiff = date2.getFullYear() - date1.getFullYear();
      const monthDiff = (yearDiff * 12) + (date2.getMonth() - date1.getMonth());

      if (monthDiff >= 12) {
        this.$confirm("时间区间大于一年，数据量过大，拒绝查询", {
          confirmButtonText: "确认",
          cancelButtonText: "取消",
          type: "warning",
        });
        done();
      } else {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
      }
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      const {month} = this.query;
      //console.log(month,"1234543")
      let values = {
        ...params,
        ...this.query
      };
      if (month) {
        values = {
          ...values,
          month1: month[0],
          month2: month[1],
        };
        values.month = null;
      }

      this.loading = true;
      declarationCompanyStatisticsList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },

    getYearMonthString(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      return `${year}-${month}`;
    },

    setSearchValue() {
      this.findObject(this.option.column, 'month').searchValue = [this.previousYearMonth, this.currentYearMonth];
      this.searchValue = [this.previousYearMonth, this.currentYearMonth];
    }
  },
  created() {
    const currentDate = new Date();
    const currentYear1 = currentDate.getFullYear();
    const currentMonth2 = String(currentDate.getMonth() + 1).padStart(2, '0');
    this.currentYearMonth = `${currentYear1}-${currentMonth2}`;
    // 获取前一个年月份
    const previousDate = new Date(currentYear1, currentDate.getMonth() - 2);
    const previousYear = previousDate.getFullYear();
    const previousMonth = String(previousDate.getMonth() + 1).padStart(2, '0');
    this.previousYearMonth = `${previousYear}-${previousMonth}`;

    this.findObject(this.option.column, 'month').searchValue = [this.previousYearMonth, this.currentYearMonth];
    this.searchValue = [this.previousYearMonth, this.currentYearMonth];
    this.onLoad(this.page, {month: this.searchValue}); // 在页面加载时调用onLoad方法，并传递初始值
  },
  mounted() {
    const currentDate = new Date();
    const currentYear1 = currentDate.getFullYear();
    const currentMonth2 = String(currentDate.getMonth() + 1).padStart(2, '0');
    this.currentYearMonth = `${currentYear1}-${currentMonth2}`;
    // 获取前一个年月份
    const previousDate = new Date(currentYear1, currentDate.getMonth() - 2);
    const previousYear = previousDate.getFullYear();
    const previousMonth = String(previousDate.getMonth() + 1).padStart(2, '0');
    this.previousYearMonth = `${previousYear}-${previousMonth}`;

    this.findObject(this.option.column, 'month').searchValue = [this.previousYearMonth, this.currentYearMonth];

    const currentYear = currentDate.getFullYear();
    const currentMonth = String(currentDate.getMonth() + 1).padStart(2, '0');
    this.searchValue = [`${currentYear}-${currentMonth}`, `${currentYear}-${currentMonth}`];
  },


};
</script>

<style>
</style>
